<?php

namespace app\api\controller\tourism;

use app\api\controller\phone\Recharge as phoneRecharge;
use app\common\controller\Api;
use app\api\model\tourism\Tourism;
use app\api\model\tourism\Order as TourismOrder;
use fast\Http;
use Symfony\Component\Cache\Adapter\DoctrineDbalAdapter;
use think\Db;
use think\Exception;
use think\Log;
use think\Request;
use WanlPay\Yansongda\Pay;
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    //获取商品列表
    public function shop(Request $request){
        $id = $request->param('id');
        $list = Tourism::where('id',$id)->find();
        $this->success('返回成功', $list);
    }
    //添加订单
    public function add(Request $request){
        $data = $request->param();
        $rule = [
            'phone' => 'require|regex:/^1[3-9]\d{9}$/',
            'name' => 'require',
            'num' => 'require',
            'code'=>'require',
            'id'=>'require',
            'event'=>'require',
        ];
        $message = [
            'phone.require' => '手机号必填',
            'name.require' => '姓名必填',
            'phone.regex' => '手机号格式不正确',
            'num.require' => '数量必填',
            'code.require' => 'code必填',
            'id.require' => '商品id必填',
            'event.require' => '事件单号必填',
        ];
        $result = $this->validate($data, $rule, $message);
        if ($result !== true) {
            // 验证失败，输出错误信息
            $this->error($result);
        } else {
            // 获取openid
            $config = get_addon_config('wanlshop');
            $params = [
                'appid'      => $config['mp_weixin']['appid'],
                'secret'     => $config['mp_weixin']['appsecret'],
                'js_code'    => $data['code'],
                'grant_type' => 'authorization_code'
            ];
            $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
            if ($result['ret']) {
                $json = (array)json_decode($result['msg'], true);
                $openid = $json['openid']??'';
                if (!$openid){
                    $this->error('获取openid失败，无法支付');
                }
            }else{
                $this->error('code失效，无法支付');
            }
            //创建订单
            $order_no = uniqid(rand(1000,9999));
            $list = Tourism::where('id',$data['id'])->find();
            if($list){
                $data = [
                    'tourism_id'=>$list->id,
                    'open_id' => $openid,
                    'phone' => $data['phone'],
                    'order_id' => $order_no,
                    'state' => 0,
                    'name'=>$data['name'],
                    'num'=>$data['num'],
                    'event'=>$data['event'],
                ];
                $order = TourismOrder::create($data);
                if($order){
                    // 发起支付
                    $payConfig = $this->getWx();
                    // 发起支付
                    $pay_data = [
                        'out_trade_no' => $order_no, // 订单号
                        'body' => '旅游订单', // 标题
                        'total_fee' => $list->price * 100, //付款金额 单位分
                        'openid' => $openid, //支付人
                    ];
                    $wechat = Pay::wechat($payConfig)->miniapp($pay_data);
                    // 返回结果
                    if ($wechat){
                        $this->success('成功',$wechat);
                    }else{
                        $this->error('支付失败');
                    }
                }
            }else{
                $this->error('商品id错误，商品不存在');
            }


        }

    }
    public function getWx(){
        $config = get_addon_config('wanlshop');
        $my_payConfig = [
            'miniapp_id' => $config['mp_weixin']['appid'], // 小程序 APPID
            'mch_id'     => $config['sdk_qq']['mch_id'],
            'key'        => $config['sdk_qq']['key'],
            'notify_url' => "https://wanlshop.enjoysix.com/api/tourism/order/notify/type/wechat",
            'log' => [ // optional
                'file'  => LOG_PATH.'wanlpay'.DS.'wechat'.'-'.date("Y-m-d").'.log',
                'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                'type' => 'single', // optional, 可选 daily.
                'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [ // optional
                'timeout' => 5.0,
                'connect_timeout' => 5.0,
            ],
        ];
        return $my_payConfig;
    }
    //支付回调
    public function notify(){
        $my_payConfig = $this->getWx();
        // 验签
        $pay = Pay::wechat($my_payConfig);
        try{
            $result = $pay->verify();
            // 查找订单
            $order = TourismOrder::where('order_id',$result['out_trade_no'])->find();
            Log::error($result);
            Log::error($order->state);
            if (!$order) {
                throw new Exception('支付订单不存在');
            }
            // 修改状态
            if ($order->state === 0){
                $order->state = 1;
                $order->save();
            }
        }catch (Exception $e) {
            Db::rollback();
            Log::error($e->getMessage());
            return $e->getMessage();
        }
        // 返回给支付接口
        return $pay->success()->send();
    }
}